package com.taokatao.cardmee.db.upgrade;

import android.content.Context;

import com.taokatao.cardmee.Utils;
import com.taokatao.cardmee.db.DaoMaster;

import org.greenrobot.greendao.database.Database;

public class UpgradeableOpenHelper extends DaoMaster.OpenHelper {

    public UpgradeableOpenHelper(Context context, String name) {
        super(context, name);
        Utils.logd("greenDAO UpgradeableOpenHelper() name:" + name);
    }

    @Override
    public void onCreate(Database db) {
        super.onCreate(db);
        Utils.logd("greenDAO onCreate");
    }

    @Override
    public void onUpgrade(Database db, int oldVersion, int newVersion) {
        Utils.logd("greenDAO Upgrading schema from version %d  to %d", oldVersion, newVersion);

        if (oldVersion < 2100000001) {
            DaoMaster.dropAllTables(db, true);
            DaoMaster.createAllTables(db, false);
            return;
        }

            /* i represent the version where the user is now and the class named with this number implies that is upgrading from i to i++ schema */
        for (int i = oldVersion; i < newVersion; i++) {
            try {
                    /* New instance of the class that migrates from i version to i++ version named DBMigratorHelper{version that the db has on this moment} */
                AbstractDBMigratorHelper migratorHelper = (AbstractDBMigratorHelper) Class.forName(AbstractDBMigratorHelper.UPGRADE_PACKAGE_NAME + ".MigrationHelper" + (i + 1)).newInstance();

                if (migratorHelper != null) {
                        /* Upgrade de db */
                    migratorHelper.onUpgrade(db);
                }
            } catch (Exception e) {
                e.printStackTrace();
                Utils.logd("greenDAO Could not migrate from schema from schema: %d to %d", i, i++);
                    /* If something fail prevent the DB to be updated to future version if the previous version has not been upgraded successfully */
                break;
            }
        }
    }
}